package cn.wizzer.app.web.commons.ext.websocket.main.base;

import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import lombok.Data;
import org.nutz.lang.Strings;

/**
 * @author 22099
 */
@Data
public class NettyRouter {

    private static final JSONObject empty = new JSONObject(0);

    private Channel income;

    private String uri;

    private JSONObject params = empty;

    private String[] uriPart;


    public NettyRouter(String uri) {
        this.setUri(uri);
    }

    public NettyRouter(String uri, Channel income) {
        this.setUri(uri);
        this.income = income;
    }

    public void setUri(String uri) {
        //包含参数-识别
        if (uri.contains("?")) {
            String[] split = uri.split("\\?");
            this.uri = split[0];
            this.uriPart = split[0].split("/");

            //参数解析
            if (Strings.isNotBlank(split[1])) {
                //json
                if (split[1].startsWith("{")) {
                    params = JSONUtil.parseToJSON(split[1]);
                }
                //url
                else {
                    String[] paramStrings = split[1].split("&");
                    params = new JSONObject(paramStrings.length);
                    for (String param : paramStrings) {
                        String[] strings = param.split("=");
                        params.put(strings[0], strings.length == 2 ? strings[1] : null);
                    }
                }
            }
        } else {
            this.uri = uri;
        }
    }

    public String getUriPart(int index) {
        if (this.uriPart.length <= index) {
            return null;
        }
        return uriPart[index];
    }

    public Object getParam(String key) {
        return this.getParams().get(key);
    }
}
